// 生产token的jwt
const jwt = require('jsonwebtoken')

// 引入 users 表
const users = require('../../models/users')

// 加密盐
const bcrypt = require("bcrypt")

// 分页查询
list = (req,res)=>{
    // console.log(req.query)
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            // token验证成功之后
            users.find({
                // 模糊查询(有就查，没有就是空)
                accunt:{$regex: req.query.accunt ? req.query.accunt : '',$options:'i'},
                username:{$regex: req.query.username ? req.query.username : '',$options:'i'},
                address:{$regex: req.query.address ? req.query.address : '',$options:'i'},
                identity:{$regex: req.query.identity ? req.query.identity : '',$options:'i'},
                // 分页查询
            }).skip((req.query.currentPage - 1) * req.query.pageSize).limit(Number(req.query.pageSize))
            .then(result=>{
                // 这里的查询是为了查总条数
                users.find({
                    // 模糊查询
                    accunt:{$regex: req.query.accunt ? req.query.accunt : '',$options:'i'},
                    username:{$regex: req.query.username ? req.query.username : '',$options:'i'},
                    address:{$regex: req.query.address ? req.query.address : '',$options:'i'},
                    identity:{$regex: req.query.identity ? req.query.identity : '',$options:'i'},
                    // 分页查询
                }).countDocuments()
                .then(result2=>{
                    res.json({code:200,data:result,total:result2})
                })
            })
        }
    });
}
// 删除
deleteUser = (req,res)=>{
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            users.findByIdAndDelete({_id:req.params.id}).then(result=>{
                res.json({code:200,data:result})
            })
        }
    });
}
// 新增
addUser = (req,res)=>{
    // console.log(req.body)
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            users.findOne({accunt:req.body.accunt}).then(result=>{
                if(result) return res.json({code:599,msg:'该用户已被注册！'})
                let user = {}
                // 这里为了能用上默认值,有的才赋值,不然就用默认值
                // user.accunt = req.body.accunt ?  req.body.accunt : '' 这样不行.会重新赋值为空字符串
                req.body.accunt ? user.accunt = req.body.accunt : ''
                req.body.password ? user.password = req.body.password : ''
                req.body.username ? user.username = req.body.username : ''
                req.body.identity ? user.identity = req.body.identity : ''
                req.body.money ? user.money = req.body.money : ''
                req.body.address ? user.address = req.body.address : ''
                req.body.avator ? user.avator = req.body.avator : ''
                bcrypt.genSalt(10,function(err,salt){
                    bcrypt.hash(user.password,salt,(err,hash)=>{
                        //箭头函数中hash就是加密后的密码
                        if(err) throw err
                        user.password = hash
                        new users(user).save().then(result=>{
                            // console.log(result)
                            res.json({code:200,data:result})
                        })
                    })
                })
            })
        }
    });
}
// 修改
updateUser = (req,res)=>{
    // console.log(req.body)
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            let user = {}
            // 这里就不能像上面那样写，可能会出现空字符串的情况
            user.accunt = req.body.accunt
            user.password = req.body.password
            user.username = req.body.username
            user.identity = req.body.identity
            user.money = req.body.money
            user.address = req.body.address
            user.avator = req.body.avator
            bcrypt.genSalt(10,function(err,salt){
                bcrypt.hash(user.password,salt,(err,hash)=>{
                    //箭头函数中hash就是加密后的密码
                    if(err) throw err
                    user.password = hash
                    // findOneAndUpdate,实际调用的是findAndModify,这个的好处是会返回文档,设置{new: true}返回更新后的文档,默认为false.
                    // 如果想用原生的findOneAndUpdate, 就设置mongoose.set('useFindAndModify', false);
                    users.updateOne({_id:req.params.id},{$set:user}).then(result=>{
                        // 这里返回的是修改之前的值
                        res.json({code:200,data:result})
                    })
                })
            })
        }
    });
}
module.exports = {
    list,deleteUser,addUser,updateUser
}